<template>
	<div>
		<el-button type="primary" size="mini" @click="onShowAddDialog" :disabled="!canEdit" class="add-btn-disable">添加</el-button>
		<el-dialog title="添加" :visible="isShowingAddDialog" :before-close="onCloseAddDialog">
			<el-form :model="addVideoData" :rules="rules" label-width="120px" ref="addFileForm" @submit.native.prevent>
				<el-form-item label="标题：" prop="title">
					<el-input v-model="addVideoData.title" placeholder="请输入标题（最多可输入 30 个字符）" clearable  :maxlength="30" class="resource-title" type="text"></el-input>
				</el-form-item>
				<el-form-item label="视频文件：" class="upload-file" prop="content">
					<el-upload accept=".mp4, .mov" ref="uploadComponent" :action="uploadFileConfig.url" :headers="uploadFileConfig.headers" limit="1" :on-success="uploadFileSuccess" :before-remove="onRemoveFile" :before-upload="beforeUpload" :on-progress="onUploadProgress">
					  <el-button type="primary">上传文件</el-button>
					</el-upload>
			  	</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="onCloseAddDialog">取 消</el-button>
				<el-button type="primary" @click="onAddVideo">确 定</el-button>
			</span>
		</el-dialog>
		<br />
		<br />
		<el-table :data="tableData" border stripe >
		  <el-table-column label="序号" type="index" align="center"></el-table-column>
		  <el-table-column label="标题" prop="title" align="center"></el-table-column>
		  <el-table-column label="文件名称" prop="fileName" align="center"></el-table-column>
		  <el-table-column label="文件大小" prop="fileSize" align="center" :formatter="formatSize"></el-table-column>
		  <el-table-column label="上传日期" prop="createdAt" align="center" :formatter="formatTime"></el-table-column>
		  <el-table-column label="链接" prop="content" align="center">
			<template slot-scope="scope">
				<el-link type="primary" class="detail-link" style="padding: 0 5px" :underline="false" :href="awsFileUrl? awsFileUrl + scope.row.href : scope.row.href" target="_blank">{{ scope.row.content }}</el-link>
			</template>
		  </el-table-column>
		  <el-table-column label="操作" align="center" width="200">
			<template slot-scope="scope">
				<el-button type="danger" size="mini" @click="onDeleteAction($event, scope.row)" :disabled="!canEdit">删除</el-button>
			</template>
		  </el-table-column>
		</el-table>
		<br />
		<!-- <page-size :pages="tablePages" @changePageSize="changePageSize" @changeCurrentPage="changeCurrentPage"></page-size> -->
	</div>
</template>

<script>

import { forceBtnBlur, fixUploadPercent } from '@/utils/MyVueUtil.js'
import { getFileSize, appendToken } from '@/utils/tool'
import PageSize from '@/views/components/PageSize.vue'
import { getBusinessResourcesBySceneId, addBusinessResource, deleteBusinessResource, getUploadFileConfig } from '@/api/api'

export default {

	components: {
		PageSize
	},

	data() {
		return {
			awsFileUrl: awsFileUrl,
			scenceId: '',
			uploadFileConfig: getUploadFileConfig(),
			canEdit: false,
			isShowingAddDialog: false,
			addVideoData: {
				title:'',
				content:'',
				fileSize: 0,
				fileName: '',
				type: 'video'
			},
			rules: {
				title: [
						{ required: true, message: '请输入标题', trigger: 'blur' },
						// { validator: validateLabelName, trigger: 'blur'}
					],
				content: [
					{ required: true, message: '请上传视频文件', trigger: 'blur' },
					// { validator: validateLabelName, trigger: 'blur'}
				]
			},
			tablePages: {
				total: 0,
				page: 1,
				pageSize: 10
			},
			tableData: []
		}
	},

	mounted(){
		this.canEdit = this.$route.query.canEdit !== 'false';
		this.scenceId = this.$route.params.id;
		this.refreshResources();
	},

	methods: {
		formatSize(row){
			return getFileSize(row.fileSize);
		},
		formatTime(row){
			return this.$moment(row.createdAt).format('YYYY-MM-DD HH:mm:ss');
		},
		onShowAddDialog() {
			if (this.tableData && this.tableData.length >= 10){
				this.$message.warning('无法添加，最多允许添加10条');
				return;
			}
			this.isShowingAddDialog = true;
		},
		onCloseAddDialog() {
			this.isShowingAddDialog = false;
			this.$refs.uploadComponent?.clearFiles();
			this.$refs.addFileForm?.resetFields();
			this.$refs.addFileForm?.clearValidate(['title', 'content']);
		},
		onAddVideo() {
			console.log('this.addVideoData.content:', this.addVideoData.content);
			this.$refs.addFileForm.validate(async success => {
				console.log('validateField result:', success);
				if (success){
					addBusinessResource(this.scenceId, this.addVideoData).then(res => {
						if (this.tableData.length === 1 && this.tablePages.page > 1){
							this.tablePages.page -= 1;
						}
						this.refreshResources();
						this.onCloseAddDialog();
						this.$message.success('添加视频资料成功！')
					}).catch(error => {
						console.log('addBusinessResource failed:', error);
						if (error.code == '1002') {
							this.$message.error(`标题已存在！`);
						} else if (error.code == '6011') {
							this.$message.warning(`无法添加，最多允许添加10条`);
						} else {
							this.$message.error(error);
						}
					});
				}
			});
		},
		beforeUpload(file) {
			console.log('file.type:', file.type);
			const isVideo = file.type === 'video/mp4' || file.type === 'video/quicktime';
			if (!isVideo) {
				this.$message.error('上传失败，仅支持上传.mp4/.mov格式的视频文件！');
				return false;
			}
			if (file.size > videoMaxSize) {
				const size = Math.floor(videoMaxSize / 1024 / 1024);
				this.$message.error(`请上传小于${size}M的文件！`);
				return false;
			}
		},
		onUploadProgress(event, file, fileList) {
			fixUploadPercent(this, event, file, fileList);
		},
		uploadFileSuccess(response, file, fileList){
			if (response.code === 200){
				this.addVideoData.content = response.data.url;
				this.addVideoData.fileName = file.name;
				this.addVideoData.fileSize = file.size;
				this.$refs.addFileForm.clearValidate(['content']);
			}
		},
		onRemoveFile(file, fileList){
			this.addVideoData.content = null;
		},
		refreshResources(){
			getBusinessResourcesBySceneId(this.scenceId, 'video', this.tablePages).then(res => {
				if (res.data.code === 200){
					this.tablePages.total = res.data.data.count;
					this.tableData = res.data.data.data.map(item => {
						return {
							...item,
							content: item.content.replace('http://', 'https://'),
							href: appendToken(item.content.replace('http://', 'https://'))
						}
					});
				}
			}).catch(error => {

			});
		},
		onDeleteAction(event, row) {
			forceBtnBlur(event);
			this.$confirm(`此操作将永久删除 "${row.title}", 是否继续?`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				deleteBusinessResource(this.scenceId, row.id).then(res => {
					this.refreshResources();
				}).catch(error => {
					console.log('deleteBusinessResource faild:', error);
					if (error.code == '6012'){
						this.$message.error('请先解除在AI工作流中该视频资料的配置再进行删除');
					} else {
						this.$message.error('删除视频资料失败！');
					}
				});
			}).catch(() => {
				this.$message.info('已取消删除');
			});
		},
		changePageSize(pageSize) {
			this.tablePages.pageSize = pageSize;
			this.refreshResources();
		},
		changeCurrentPage(page){
			this.tablePages.page = page;
			this.refreshResources();
		},
	}

}

</script>

<style lang="less" scoped>
.resource-title {
	width: 80%;
}
.resource-file-container {
	display: flex;
}
.resource-file {
	width: 40%;
}
.add-btn-disable[disabled] {
	background: #a0cfff !important;
}
.el-form {
	.el-form-item {
		/deep/ .el-form-item__label {
			text-align: left;
			padding-left: 10px;
		}
	}
}
.upload-file {
	/deep/ .el-input__inner{
		border-width: 0px;
		padding-left: 0px;
	}
}

.detail-link {
	.el-link--inner {
		color: #6384fe;
		border-bottom: 1px solid #6384fe;
	}
}
</style>
